//
//  WSGradientColorView.m
//  WebComics
//
//  Created by zjw1 on 2017/10/10.
//  Copyright © 2018年 WEBCOMICS HOLDINGS. All rights reserved.
//

#import "WSGradientColorView.h"

@interface WSGradientColorView ()

@property (nonatomic, assign) CGRect gradientLayerFrame;
@property (nonatomic, strong) CAGradientLayer *gradientLayer;

@end


@implementation WSGradientColorView

- (void)layoutSubviews {
    [super layoutSubviews];
    _gradientLayer.frame = self.bounds;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    [self.gradientLayer removeFromSuperlayer];
    [self setupGradientLayer];
}

- (void)setLayerFrame:(CGRect)frame {
    self.gradientLayerFrame = frame;
    self.gradientLayer.frame = self.gradientLayerFrame;
}

- (void)setupGradientLayer {
    
    CAGradientLayer *layer = [[CAGradientLayer alloc] init];
    CGRect frame = self.bounds;
    if (CGRectEqualToRect(self.gradientLayerFrame, CGRectZero)) {
        layer.frame = frame;
    } else {
        layer.frame = self.gradientLayerFrame;
    }

    if (self.color1 && self.color2) {
        layer.colors = @[(__bridge id)self.color1.CGColor,
                         (__bridge id)self.color2.CGColor];
    } else {
        layer.colors = @[(__bridge id)[UIColor colorFromHexRGB:@"FDF0BB"].CGColor,
                         (__bridge id)[UIColor colorFromHexRGB:@"FDF0BB" alpha:0].CGColor];
    }


    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(1, 0);
    [self.layer insertSublayer:layer atIndex:0];
    self.gradientLayer = layer;
}

- (void)resetCorlor1:(UIColor *)color1 color2:(UIColor *)color2 {
    _color1 = color1;
    _color2 = color2;
    
    [self.gradientLayer removeFromSuperlayer];
    self.gradientLayer = nil;
    
    [self setupGradientLayer];
}

- (void)resetCorlorByStyleDidChange {
    if (@available(iOS 12.0, *)) {
        if (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark) {
            [self resetCorlor1:UIColor.bg_gray_f2f2f2 color2:UIColor.bg_gray_f2f2f2];
        }
        else {
            [self resetCorlor1:[UIColor colorFromHexRGB:@"FDF0BB"] color2:[UIColor colorFromHexRGB:@"FDF0BB" alpha:0]];
        }
    } else {
        [self resetCorlor1:[UIColor colorFromHexRGB:@"FDF0BB"] color2:[UIColor colorFromHexRGB:@"FDF0BB" alpha:0]];
    }
}


/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
